﻿using System;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace AspDotnetPractice.UserControl
{
    public class Another : WebControl
    {
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            
            RegisterClientScript();
            RegisterStyleSheet();
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            base.RenderContents(writer);
            
            writer.AddAttribute(HtmlTextWriterAttribute.Class,"Box");
            writer.RenderBeginTag(HtmlTextWriterTag.Div);
            writer.RenderEndTag();
        }

        private void RegisterClientScript()
        {
            Page.ClientScript.RegisterClientScriptResource(GetType(), "AspDotnetPractice.UserControl.Box.js");
        }

        private void RegisterStyleSheet()
        {
            string webUrl = Page.ClientScript.GetWebResourceUrl(GetType(), "AspDotnetPractice.UserControl.Box.css");
            HtmlLink link = new HtmlLink { Href = webUrl };
            link.Attributes.Add("rel", "stylesheet");
            link.Attributes.Add("type", "text/css");
            if (StyleSheetIncluded(Page.Header.Controls,link)) return;
            Page.Header.Controls.Add(link);
        }
        
        private bool StyleSheetIncluded(ControlCollection controls,HtmlLink link)
        {
            var included = false;
            foreach (var htmlLink in controls.OfType<HtmlLink>())
            {
                included = (link.Href == htmlLink.Href);
            }
            return included;
        }

    }
}